package org.lyd.spring.ioc.PostProcessor;

import org.lyd.spring.ioc.annotation.UUID;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * @Author:lyd
 **/
//拦截容器中所有的bean
@Component
public class MyBeanPostProcessor implements BeanPostProcessor{


    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        Field[] fields = bean.getClass().getDeclaredFields();
        for (Field field : fields) {
            //field.isAnnotationPresent(UUID.class)
            if (AnnotationUtils.findAnnotation(field, UUID.class)!=null && field.getType().equals(String.class)) {
                System.out.println("找到了UUID注解");
                field.setAccessible(true);
                try {
                    field.set(bean, java.util.UUID.randomUUID().toString());
                    System.out.println("hhhh");
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return bean;
    }
}
